""" _*_ coding : utf-8 _*_
 @Time: 2025/8/20 16:35
 @Author : 虎
 @File : URLS
 @Project : education
"""
from fastapi import HTTPException, status
from apps.schemas.login import LoginRequest
from fastapi import APIRouter, HTTPException
from apps.models import Login, Course
from fastapi import APIRouter, HTTPException, Depends
from passlib.context import CryptContext
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request
import logging
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.staticfiles import StaticFiles
import os
import uuid
from fastapi import Form, File, UploadFile, HTTPException, Depends
from typing import Optional
from ..UsersManger.config import get_current_user, JWTUtils
from apps.schemas.login import LoginRequest
# 添加一个调试端点来检查token内容
from fastapi import Header
# 创建上传目录（如果不存在）
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
course = APIRouter()


# 获取课程列表
from fastapi import HTTPException, status


@course.get("/courseList")
async def get_current_user_courseList(current_user: dict = Depends(get_current_user)):
    """
    prefetch_related()查外键
    只有管理员可以访问
    """
    # # 检查用户角色是否为管理员
    # if current_user.get("role") != "admin":
    #     raise HTTPException(
    #         status_code=status.HTTP_403_FORBIDDEN,
    #         detail="权限不足，需要管理员权限"
    #     )
    # 只有管理员才能执行下面的代码
    courseList = await Course.all().values("id", "name", "picture", "content", "video", "status", "extral_1",
                                           "extral_2", "extral_3", "user_id__name")
    print(courseList)
    return {"code": 200, "data": courseList}


# 添加课程列表
@course.post("/addCourse")
async def addCourse(
        name: str = Form(...),
        video: str = Form(None),
        content: str = Form(None),
        status: str = Form("active"),
        extral_1: str = Form(None),
        extral_2: str = Form(None),
        extral_3: str = Form(None),
        picture: UploadFile = File(None)
):
    """
    添加课程 - 使用参数注入
    """
    try:
        print("=== 接收到的参数 ===")
        print(f"name: {name}")
        print(f"video: {video}")
        print(f"content: {content}")
        print(f"status: {status}")
        print(f"extral_1: {extral_1}")
        print(f"extral_2: {extral_2}")
        print(f"extral_3: {extral_3}")
        print(f"picture: {picture.filename if picture else None}")

        # 处理图片上传
        picture_filename = None
        if picture and picture.filename:
            print(f"✅ 接收到图片文件: {picture.filename} (大小: {getattr(picture, 'size', 'unknown')} bytes)")

            # 验证文件类型
            allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp'}
            file_extension = os.path.splitext(picture.filename)[1].lower()

            if file_extension not in allowed_extensions:
                raise HTTPException(status_code=400, detail="不支持的文件类型，只支持: jpg, jpeg, png, gif, webp")

            # 生成唯一文件名
            file_extension = file_extension.lstrip('.')
            picture_filename = f"{uuid.uuid4().hex}.{file_extension}"
            picture_path = os.path.join(UPLOAD_DIR, picture_filename)

            # 保存文件
            contents = await picture.read()

            # 验证文件大小
            if len(contents) > 5 * 1024 * 1024:
                raise HTTPException(status_code=400, detail="文件大小不能超过5MB")

            # 确保上传目录存在
            os.makedirs(UPLOAD_DIR, exist_ok=True)

            with open(picture_path, "wb") as buffer:
                buffer.write(contents)

            print(f"✅ 文件保存成功: {picture_filename}")

        # 准备课程数据
        course_data = {
            "name": name.strip(),
            "video": video.strip() if video and video.strip() else None,
            "content": content.strip() if content and content.strip() else None,
            "status": status.strip() if status else "active",
            "extral_1": extral_1.strip() if extral_1 and extral_1.strip() else None,
            "extral_2": extral_2.strip() if extral_2 and extral_2.strip() else None,
            "extral_3": extral_3.strip() if extral_3 and extral_3.strip() else None,
            "picture": picture_filename,
            "user_id_id": 1  # 使用管理员用户ID
        }

        print("=== 最终课程数据 ===")
        for key, value in course_data.items():
            print(f"{key}: {value}")

        # 创建课程
        course = await Course.create(**course_data)
        print("✅ 课程创建成功，ID:", course.id)

        return {"code": 200, "data": course, "message": "课程创建成功"}

    except HTTPException:
        raise
    except Exception as e:
        print(f"❌ 创建课程时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")


#删除
@course.delete("/deleteCourse/{id}")
async def deleteCourse(id: int):
    """
    删除课程
    """
    course = await Course.filter(id=id).first()
    if course:
        await course.delete()
        return {"code": 200, "msg": "删除成功"}
    return {"code": 404, "msg": "课程不存在"}

